package com.ysstech.reportworld.controller;


import com.alibaba.fastjson.JSONArray;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.fileutil.FileWriterUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.reportworld.entity.Customer;
import com.ysstech.reportworld.entity.DataCustomer;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.enums.ReportWorldFileNameEnum;
import com.ysstech.reportworld.enums.ReportWorldStatusEnum;
import com.ysstech.reportworld.service.CustomerService;
import com.ysstech.reportworld.service.ModularService;
import com.ysstech.reportworld.service.ReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报表世界客户信息 前端控制器
 * </p>
 *
 * @author lishuangliang
 * @since 2022-04-28
 */
@Controller
@Slf4j
@Api(tags = "报表世界客户管理api")
@RequestMapping("/customer")
public class CustomerController extends BaseController {


    @Autowired
    private CustomerService customerService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private ModularService modularService;

    /**
     * 跳转客户信息页面
     *
     * @return
     * @throws Exception
     */
    @YssPermissions(value = {"reportworld:customer"})
    @ApiOperation(value = "跳转客户管理页面")
    @YssLog(module = "客户管理", remark = "跳转客户管理页面")
    @RequestMapping(value = "/page")
    public String page() throws Exception {
        return "reportworld/customer";
    }

    /**
     * 加载客户树信息
     *
     * @return
     * @throws Exception
     */
    @YssPermissions(value = {"reportworld:customer"})
    @ApiOperation(value = "获取客户树信息")
    @YssLog(module = "客户管理", remark = "获取客户树信息")
    @RequestMapping(value = "/queryCustomerTree")
    @ResponseBody
    public RestResult queryCustomerTree() throws Exception {
        return ResultGenerator.getSuccessResult("获取客户信息成功！",
                customerService.queryCustomerTree());
    }

    @YssPermissions(value = {"reportworld:customer"})
    @ApiOperation(value = "客户管理初始化")
    @YssLog(module = "客户管理", remark = "客户管理初始化")
    @PostMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<TreeNode> listCustomer = customerService.queryCustomerTree();
        map.put("listCustomer", listCustomer);
        // 所属模块
        List<TreeNode> listModular = modularService.queryModularTree();
        map.put("listModular", listModular);
        // 字段所属报表
        List<TreeNode> listReport = reportService.queryReportTree();
        map.put("listReport", listReport);
        // 版本
        List<Dicvalue> listVersion = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_VERSION.getCode());
        map.put("listVersion", listVersion);
        return ResultGenerator.getSuccessResult("获取页面初始化信息成功", map);
    }

    /**
     * 获取一个客户的详细信息
     *
     * @param id
     * @return
     * @throws Exception
     */
    @YssPermissions(value = {"reportworld:customer"})
    @ApiOperation(value = "获取客户信息")
    @YssLog(module = "客户管理", remark = "获取客户信息")
    @RequestMapping(value = "/queryReportCustomerInfo")
    @ResponseBody
    public RestResult queryReportCustomerInfo(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException("获取客户信息失败，请稍后重试！");
        }
        Customer customer = customerService.getById(id);
        if (StringUtils.isNotBlank(customer.getStrModular())) {
            StringBuffer bufferModular = new StringBuffer();
            List<String> idsModular = JSONArray.parseArray(customer.getStrModular(), String.class);
            for (String ids : idsModular) {
                bufferModular.append(ids).append(",");
            }
            customer.setStrModular(bufferModular.deleteCharAt(bufferModular.length() - 1).toString());
        }
        if (StringUtils.isNotBlank(customer.getStrReport())) {
            List<String> idsReport = JSONArray.parseArray(customer.getStrReport(), String.class);
            StringBuffer bufferReport = new StringBuffer();
            for (String ids : idsReport) {
                bufferReport.append(ids).append(",");
            }
            customer.setStrReport(bufferReport.deleteCharAt(bufferReport.length() - 1).toString());
        }
        return ResultGenerator.getSuccessResult("获取客户信息成功！", customer);
    }

    /**
     * 新增客户的方法
     *
     * @param customer
     * @return
     */
    @YssPermissions(value = {"reportworld:customer:add"})
    @ApiOperation(value = "新增客户信息")
    @YssLog(module = "客户管理", remark = "新增客户信息")
    @RequestMapping(value = "/add")
    @ResponseBody
    public RestResult add(Customer customer) throws Exception {
        customerService.addCustomer(customer);
        return ResultGenerator.getSuccessResult("新增客户信息成功！");
    }

    /**
     * 修改客户信息
     *
     * @param customer
     * @return
     */
    @YssPermissions(value = {"reportworld:customer:edit"})
    @ApiOperation(value = "修改客户信息")
    @YssLog(module = "客户管理", remark = "修改客户信息")
    @RequestMapping(value = "/edit")
    @ResponseBody
    public RestResult edit(Customer customer) throws Exception {
        customerService.editCustomer(customer);
        return ResultGenerator.getSuccessResult("修改客户信息成功！");
    }

    /**
     * 删除客户信息
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:customer:del"})
    @ApiOperation(value = "删除客户信息")
    @YssLog(module = "客户管理", remark = "删除客户信息")
    @RequestMapping(value = "/del")
    @ResponseBody
    public RestResult delete(String id) throws Exception {
        customerService.delCustomer(id);
        return ResultGenerator.getSuccessResult("删除客户信息成功！");
    }


    /**
     * 获取客户对应表信息
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:customer:query"})
    @ApiOperation(value = "客户对应表信息")
    @YssLog(module = "客户管理", remark = "客户对应表信息")
    @RequestMapping(value = "/getTableInfo")
    @ResponseBody
    public RestResult getTableInfo(DataCustomer dataCustomer) throws Exception {
        if (null == dataCustomer || StringUtils.isBlank(dataCustomer.getCustomerId())) {
            throw new BusinessException("获取报表对应表信息失败，请稍后重试！");
        }
        return ResultGenerator.getSuccessResult("获取报表对应表信息成功！", customerService.getTableInfo(dataCustomer));
    }

    /**
     * 保存客户对应的模块报表信息
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:customer:manmger"})
    @ApiOperation(value = "客户信息管理")
    @YssLog(module = "客户管理", remark = "客户信息管理")
    @RequestMapping(value = "/doCustomerManger")
    @ResponseBody
    public RestResult doCustomerManger(Customer customer) throws Exception {
        if (null == customer || StringUtils.isBlank(customer.getId())
               /* || StringUtils.isBlank(customer.getSelReport())*/ || StringUtils.isBlank(customer.getSelModular())) {
            throw new BusinessException("保存客户信息管理失败，请稍后重试！");
        }
        customer.setStrReport(customer.getSelReport());
        customer.setStrModular(customer.getSelModular());
        customer.setEditUser(redisCacheManager.getLoginUserInfo().getLoginId());
        customer.setEditTime(LocalDateTime.now());
        customerService.updateById(customer);
        return ResultGenerator.getSuccessResult("保存客户信息管理信息成功！");
    }

    /**
     * 导出客户的密文文件提供给升级工具使用
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:customer:base64"})
    @ApiOperation(value = "导出客户许可文件")
    @YssLog(module = "客户管理", remark = "导出客户许可文件")
    @RequestMapping(value = "/customerBase64")
    @ResponseBody
    public void customerBase64(HttpServletResponse response, Customer customer) throws Exception {
        if (null == customer || StringUtils.isBlank(customer.getId())) {
            throw new BusinessException("没有获取到客户信息，请稍后重试！");
        }
        String strCustomer = customerService.customerBase64(customer);
        FileWriterUtil.downloadFileBuffer(response, strCustomer, customer.getName() + "_" +
                ReportWorldFileNameEnum.CUSTOMER_LIC.getCode(), ReportWorldFileNameEnum.CUSTOMER_LIC.getDesc());
    }
}
